<?php
require 'TVB/pms/pdes/common/bootstrap.php';

if (empty($_REQUEST['q'])) {
    exit('[]');
}

$sql = "
    SELECT `id`, `master` , 
      CONCAT(`chi_last_name`, `chi_first_name`) AS chi,
      RTRIM(
        CONCAT(
          CASE WHEN LENGTH(`eng_last_name`)>0 THEN CONCAT(`eng_last_name`,' ') ELSE `eng_last_name` END,
          `eng_first_name1`
        )
      ) AS eng1,
      RTRIM(
        CONCAT(
          CASE WHEN LENGTH(`eng_first_name2`)>0 THEN CONCAT(`eng_first_name2`,' ') ELSE `eng_first_name1` END,
          `eng_last_name`
        )
      ) AS eng2, 
      `others`, `remark`
    FROM `cast_dictionary` HAVING (
     master LIKE :condition OR
     chi    LIKE :condition OR
     eng1   LIKE :condition OR
     eng2   LIKE :condition OR
     others LIKE :condition OR
     remark LIKE :condition
    )
";
$param = array(
    ':condition'    => '%' . $_REQUEST['q'] . '%'
);
$data = Model::selectBySql($sql, $param);

function replace_null(&$item){ $item = empty($item) ? "" : $item; }

$ret = array();
if (!empty($data)) {
    foreach ($data as $row) {
        $list = array();
        $list['id'] = $row['id'];
        unset($row['id']);
        $list['name'] = array_values($row); 
		array_walk($list['name'],'replace_null');
        $list['type'] = isset($_REQUEST['type']) ? $_REQUEST['type'] : 'name';
        $ret[] = $list;
    }
}

exit(json_encode($ret));
?>
